package com.alibaba.cloud.encry;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.apache.commons.codec.binary.Hex;


/**
 * The Class PBE.
 *
 * @ClassName: PBEStrategy
 * @Description: 基于口令的加密（password），对称 + 消息摘要
 * @author: zhb zhb1316783262@163.com
 * @date: 2018年3月13日 下午5:25:21
 */
public class PBE {
	
	/** 解密. */
	private static Cipher cipher;
	
	/** 密钥. */
	private static SecretKey secretKey;
	
	/** The pbe parameter spec. */
	private static PBEParameterSpec pbeParameterSpec;

	/** The Constant tocken. */
	private static final String tocken = "pig";
	static {
		try {
			SecureRandom secureRandom = new SecureRandom();
			byte[] salt = secureRandom.generateSeed(8);
			PBEKeySpec pbeKeySpec = new PBEKeySpec(tocken.toCharArray());
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
			secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
			pbeParameterSpec = new PBEParameterSpec(salt, 100);
			cipher = Cipher.getInstance("PBEWITHMD5andDES");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Encode.
	 *
	 * @param src the src
	 * @return the string
	 */
	public String encode(String src) {
		try {
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
			byte[] resultBytes = cipher.doFinal(src.getBytes());
			return Hex.encodeHexString(resultBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Decode.
	 *
	 * @param src the src
	 * @return the string
	 */
	public String decode(String src) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
			byte[] result = Hex.decodeHex(src.toCharArray());
			return new String(cipher.doFinal(result));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}